package com.vm.osm.business.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.vm.osm.business.dao.*;
import com.vm.osm.business.dto.CreateNotifyReq;
import com.vm.osm.business.dto.req.checkPlan.ReqSelectTask;
import com.vm.osm.business.dto.req.orderInst.*;
import com.vm.osm.business.dto.rsp.failOrder.OrderFlowInfo;
import com.vm.osm.business.dto.rsp.message.RspMessage;
import com.vm.osm.business.dto.rsp.message.RspMessagePage;
import com.vm.osm.business.dto.rsp.orderInst.*;
import com.vm.osm.business.entity.*;
import com.vm.osm.business.service.ICheckPlanInstService;
import com.vm.osm.business.service.IOsmDispatchRuleService;
import com.vm.osm.business.util.*;
import com.vma.eams.spring.boot.log.LogCollector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Created by chenzui on 2018/3/26.
 */
@Service
public class CheckPlanInstServiceImpl implements ICheckPlanInstService {

    @Autowired
    private OsmCheckPlanInstMapper osmCheckPlanInstMapper;

    @Autowired
    private OsmOrderFlowMapper osmOrderFlowMapper;

    @Autowired
    private OsmCheckKpiValueMapper osmCheckKpiValueMapper;

    @Autowired
    private LoopTaskOrderMapper loopTaskOrderMapper;

    @Autowired
    private OsmCheckPlanMapper osmCheckPlanMapper;

    @Autowired
    private OsmOrderEvaluateMapper osmOrderEvaluateMapper;

    @Autowired
    private IOsmDispatchRuleService osmDispatchRuleService;

    @Autowired
    private NotifyUtil notifyUtil;


    @Override
    public void agree(String orderId, String staffId, String staffName, String headIcon) {
        OsmCheckPlanInst order = osmCheckPlanInstMapper.selectByPrimaryKey(orderId);
        order.setStatus("6");//处理中
        order.setUpdateTime(new Date());
        order.setAcceptStaffId(staffId);
        order.setAcceptStaffName(staffName);
        osmCheckPlanInstMapper.updateByPrimaryKeySelective(order);

        //记录操作流程节点
        OsmOrderFlow osmOrderFlow = new OsmOrderFlow();
        osmOrderFlow.setSimpleDesc("接单");
        osmOrderFlow.setOperateUserId(staffId);
        osmOrderFlow.setId(UuidUtil.getRandomUuid());
        osmOrderFlow.setStatus(new Byte("1"));
        osmOrderFlow.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setUpdateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setOperateUserName(staffName);
        osmOrderFlow.setOrderId(orderId);
        osmOrderFlow.setOperateUserIcon(headIcon);
        osmOrderFlowMapper.insertSelective(osmOrderFlow);
        LogCollector.INSTANCE.put("工单号",order.getOrderNbr());

    }

    @Override
    public void disagree(String orderId, String type, String reason, String staffId, String staffName, String headIcon) {
        OsmCheckPlanInst order = osmCheckPlanInstMapper.selectByPrimaryKey(orderId);
        order.setStatus("3");//等待分配
        order.setUpdateTime(new Date());
        order.setAcceptStaffId(staffId);
        osmCheckPlanInstMapper.updateByPrimaryKeySelective(order);

        //记录操作流程节点
        OsmOrderFlow osmOrderFlow = new OsmOrderFlow();
        osmOrderFlow.setSimpleDesc("拒绝接单");
        osmOrderFlow.setOperateUserId(staffId);
        osmOrderFlow.setId(UuidUtil.getRandomUuid());
        osmOrderFlow.setStatus(new Byte("1"));
        osmOrderFlow.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setUpdateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setOperateUserName(staffName);
        osmOrderFlow.setOrderId(orderId);
        osmOrderFlow.setOperateUserIcon(headIcon);
        osmOrderFlow.setRefuseType(Integer.valueOf(type));
        osmOrderFlow.setRefuseReason(reason);
        osmOrderFlowMapper.insertSelective(osmOrderFlow);
    }

    @Override
    public void turn(ReqTurnOrder reqTurnOrder) {
        OsmOrderFlow osmOrderFlow = new OsmOrderFlow();
        String desc = "维护人员"+reqTurnOrder.getStaff_name()+"在"+ DateFormatUtils.formate(new Date())+
                "转单给"+reqTurnOrder.getTarget_staff_name()+"备注："+reqTurnOrder.getRemark();
        osmOrderFlow.setSimpleDesc(desc);
        osmOrderFlow.setOperateUserId(reqTurnOrder.getStaff_id());
        osmOrderFlow.setId(UuidUtil.getRandomUuid());
        osmOrderFlow.setStatus(new Byte("1"));
        osmOrderFlow.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setUpdateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setOperateUserName(reqTurnOrder.getStaff_name());
        osmOrderFlow.setOrderId(reqTurnOrder.getOrder_id());
        osmOrderFlow.setOperateUserIcon(reqTurnOrder.getHead_icon());
        osmOrderFlowMapper.insertSelective(osmOrderFlow);

        OsmCheckPlanInst order = osmCheckPlanInstMapper.selectByPrimaryKey(reqTurnOrder.getOrder_id());
        order.setStatus("5");//处理中
        order.setAcceptStaffId(reqTurnOrder.getTarget_staff_id());
        osmCheckPlanInstMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public TaskOrderInfo getOrderInfo(String id) {
        //查巡检任务主体信息
        TaskOrderInfo orderInfo = osmCheckPlanInstMapper.queryOrderInfoById(id);

        List<OrderFlowInfo> flowInfos = osmOrderFlowMapper.queryFlowInfosByOrderId(id);

        //查巡检内容分类
        String contentId = orderInfo.getPlan_content();
        List<ContentType> types = osmCheckPlanInstMapper.queryTypesByContentId(contentId);

        //查每个巡检分类下有哪些巡检任务
        for(ContentType type:types){
            List<TaskItem> items = osmCheckPlanInstMapper.queryTaskItemByTypeId(type.getId());

            for (TaskItem item:items) {
                List<Kpi> kpis = osmCheckPlanInstMapper.queryKpis(id,item.getId());

                for(Kpi kpi:kpis){
                    List<KpiValues> values = osmCheckPlanInstMapper.getKpiValuesById(kpi.getId(),kpi.getKpi_version());
                    List choose = osmCheckPlanInstMapper.queryChooseValue(kpi.getId(),id,item.getId());
                    kpi.setResult(choose);
                    kpi.setValues(values);
                }
                item.setKpis(kpis);
            }
            type.setItems(items);
        }

        orderInfo.setTypes(types);
        orderInfo.setFlows(flowInfos);

        orderInfo.setEvaluate(osmOrderEvaluateMapper.queryEvaluateByOrder(id));

        return orderInfo;
    }

    @Override
    public void updateLoopTask(ReqUpdateLoopTask reqUpdateLoopTask,HttpServletRequest request) {
        List<ReqUpdateKpiValue> kpiValues = reqUpdateLoopTask.getValues();
        String orderId = reqUpdateLoopTask.getOrder_id();
        OsmCheckPlanInst inst = osmCheckPlanInstMapper.selectByPrimaryKey(orderId);
        inst.setUpdateTime(new Date());
        inst.setCheckRemark(reqUpdateLoopTask.getCheck_remark());
        inst.setCheckResult(reqUpdateLoopTask.getCheck_result());
        osmCheckPlanInstMapper.deleteKpi(reqUpdateLoopTask.getOrder_id());
        OsmCheckKpiValue checkValue = new OsmCheckKpiValue();
        for (ReqUpdateKpiValue kv:kpiValues) {
            checkValue.setKpiId(kv.getKpi_id());
            checkValue.setKpiValue(kv.getValue());
            checkValue.setCheckOrderId(orderId);
            checkValue.setItemId(kv.getItem_id());
            checkValue.setId(UuidUtil.getRandomUuid());
            osmCheckKpiValueMapper.insertSelective(checkValue);
        }

        if("1".equals(reqUpdateLoopTask.getType())){

        }else {
            String content = "工单【"+inst.getCheckTitle() +"】已处理完成，请确认处理结果";
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("order_type","1");
            jsonObject.addProperty("type","1");
            jsonObject.addProperty("order_id",inst.getId());
            String extra = GsonUtil.toJson(jsonObject);
            String title = "工单处理完成";
            OsmCheckPlan osmCheckPlan = osmCheckPlanMapper.selectByPrimaryKey(inst.getCheckPlanId());
            String sender = inst.getAcceptStaffId();
            String target = osmCheckPlan.getSubmitStaffId();
            CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,sender,target,osmCheckPlan.getEnterpriseId());

            notifyUtil.send(createNotifyReq);

            inst.setStatus("7");
            inst.setRealExcuteTime(DateFormatUtils.formate(new Date(),DateFormatUtils.SPLIT_PATTERN_DATETIME));
            LogCollector.INSTANCE.put("工单号",inst.getOrderNbr());

            OsmOrderFlow osmOrderFlow = new OsmOrderFlow();
            osmOrderFlow.setSimpleDesc("处理完成");
            osmOrderFlow.setOperateUserId(UserDataUtil.getStaffId(request));
            osmOrderFlow.setId(UuidUtil.getRandomUuid());
            osmOrderFlow.setStatus(new Byte("1"));
            osmOrderFlow.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
            osmOrderFlow.setUpdateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
            osmOrderFlow.setOperateUserName(UserDataUtil.getStaffName(request));
            osmOrderFlow.setOrderId(inst.getId());
            osmOrderFlow.setOperateUserIcon(UserDataUtil.getStaffHeadImg(request));
            osmOrderFlowMapper.insertSelective(osmOrderFlow);
        }
        osmCheckPlanInstMapper.updateByPrimaryKeySelective(inst);

    }

    @Override
    public RspOrderPage queryLoops(Integer pageNum, Integer pageSize,String enterpriseId, String staffId) {
        RspOrderPage rspOrderPage = new RspOrderPage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<OrderInfo> dataList = loopTaskOrderMapper.queryLoops(enterpriseId,staffId);
        rspOrderPage.setData_list(dataList);
        rspOrderPage.setTotal_num(page.getTotal());
        rspOrderPage.setPage_num(page.getPageNum());
        rspOrderPage.setPage_size(page.getPageSize());
        return rspOrderPage;
    }

    @Override
    public RspOrderPage queryLoop(ReqSelectTask reqSelectTask, HttpServletRequest request) {
        RspOrderPage rspOrderPage = new RspOrderPage();
        Page page = PageHelper.startPage(reqSelectTask.getPage_num(),reqSelectTask.getPage_size(),true);
        List<OrderInfo> dataList = loopTaskOrderMapper.queryLoop(reqSelectTask);
        rspOrderPage.setData_list(dataList);
        rspOrderPage.setTotal_num(page.getTotal());
        rspOrderPage.setPage_num(page.getPageNum());
        rspOrderPage.setPage_size(page.getPageSize());
        return rspOrderPage;
    }

    @Override
    public RspOrderPage queryLoops(String checkPlanId, Integer pageNum, Integer pageSize) {
        RspOrderPage rspOrderPage = new RspOrderPage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<OrderInfo> dataList = loopTaskOrderMapper.queryLoopsByPlanId(checkPlanId);
        rspOrderPage.setData_list(dataList);
        rspOrderPage.setTotal_num(page.getTotal());
        rspOrderPage.setPage_num(page.getPageNum());
        rspOrderPage.setPage_size(page.getPageSize());
        return rspOrderPage;
    }

    @Override
    public void outAccept(ReqAcceptByDept reqAcceptByDept, HttpServletRequest request) {
        OsmCheckPlanInst order = osmCheckPlanInstMapper.selectByPrimaryKey(reqAcceptByDept.getOrder_id());
        if(!order.getStatus().equals("12")){
            return;
        }


        if("1".equals(reqAcceptByDept.getType())){
            //自动分发
//            osmDispatchRuleService.orderAutoDispatch(order.getId());

        }else if("2".equals(reqAcceptByDept.getType())){
            //直接指定
            order.setAcceptStaffId(reqAcceptByDept.getStaff_id());

            order.setAcceptStaffName(reqAcceptByDept.getStaff_name());

            order.setStatus("5");//待接单

            order.setUpdateTime(new Date());

            osmCheckPlanInstMapper.updateByPrimaryKeySelective(order);

        }




        //记录操作流程节点
        OsmOrderFlow osmOrderFlow = new OsmOrderFlow();
        osmOrderFlow.setSimpleDesc("受理外部巡检单据");
        osmOrderFlow.setOperateUserId(reqAcceptByDept.getStaff_id());
        osmOrderFlow.setId(UuidUtil.getRandomUuid());
        osmOrderFlow.setStatus(new Byte("1"));
        osmOrderFlow.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setUpdateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setOperateUserName(reqAcceptByDept.getStaff_name());
        osmOrderFlow.setOrderId(reqAcceptByDept.getOrder_id());
        osmOrderFlow.setOperateUserIcon(reqAcceptByDept.getStaff_icon());
        osmOrderFlowMapper.insertSelective(osmOrderFlow);
        LogCollector.INSTANCE.put("工单号",order.getOrderNbr());

    }

    @Override
    public void outRefuse(String orderId,String type,String reason, HttpServletRequest request) {
        OsmCheckPlanInst order = osmCheckPlanInstMapper.selectByPrimaryKey(orderId);
        order.setStatus("3");//等待分配
        order.setUpdateTime(new Date());
        order.setSourceEnterpriseId(order.getSourceEnterpriseId()+"-back");
        osmCheckPlanInstMapper.updateByPrimaryKeySelective(order);
        //记录操作流程节点
        OsmOrderFlow osmOrderFlow = new OsmOrderFlow();
        osmOrderFlow.setSimpleDesc("拒绝受理外部巡检单据"+reason);
        osmOrderFlow.setOperateUserId(UserDataUtil.getStaffId(request));
        osmOrderFlow.setId(UuidUtil.getRandomUuid());
        osmOrderFlow.setStatus(new Byte("1"));
        osmOrderFlow.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setUpdateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setOperateUserName(UserDataUtil.getStaffName(request));
        osmOrderFlow.setOrderId(orderId);
        osmOrderFlow.setOperateUserIcon(UserDataUtil.getStaffHeadImg(request));
        osmOrderFlowMapper.insertSelective(osmOrderFlow);

        String planId = order.getCheckPlanId();
        OsmCheckPlan plan = osmCheckPlanMapper.selectByPrimaryKey(planId);
        String enterpriseId = plan.getEnterpriseId();
        order.setId(UuidUtil.getRandomUuid());
        order.setEnterpriseId(enterpriseId);
        osmCheckPlanInstMapper.insertSelective(order);

        OsmOrderFlow backFlow = new OsmOrderFlow();
        backFlow.setSimpleDesc("服务商退回巡检单据");
        backFlow.setOperateUserId(UserDataUtil.getStaffId(request));
        backFlow.setId(UuidUtil.getRandomUuid());
        backFlow.setStatus(new Byte("1"));
        backFlow.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        backFlow.setUpdateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        backFlow.setOperateUserName(UserDataUtil.getUserSelectedEnterpriseName(request));
        backFlow.setOrderId(order.getId());
        backFlow.setOperateUserIcon(UserDataUtil.getStaffHeadImg(request));
        osmOrderFlowMapper.insertSelective(backFlow);

    }

    @Override
    public void catchOrder(String orderId, HttpServletRequest request) {
        OsmCheckPlanInst order = osmCheckPlanInstMapper.selectByPrimaryKey(orderId);
        if(order.getStatus().equals("6")){
            // TODO: 2018/4/8 业务异常
        }else {
            order.setUpdateTime(new Date());
            order.setStatus("6");//处理中
            order.setAcceptStaffName(UserDataUtil.getStaffName(request));
            order.setAcceptStaffId(UserDataUtil.getStaffId(request));
            osmCheckPlanInstMapper.updateByPrimaryKeySelective(order);

            //记录操作流程节点
            OsmOrderFlow osmOrderFlow = new OsmOrderFlow();
            osmOrderFlow.setSimpleDesc("抢单成功");
            osmOrderFlow.setOperateUserId(UserDataUtil.getStaffId(request));
            osmOrderFlow.setId(UuidUtil.getRandomUuid());
            osmOrderFlow.setStatus(new Byte("1"));
            osmOrderFlow.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
            osmOrderFlow.setUpdateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
            osmOrderFlow.setOperateUserName(UserDataUtil.getStaffName(request));
            osmOrderFlow.setOrderId(orderId);
            osmOrderFlow.setOperateUserIcon(UserDataUtil.getStaffHeadImg(request));
            osmOrderFlowMapper.insertSelective(osmOrderFlow);
        }
    }

    @Override
    public void again(HttpServletRequest request, String orderId, String remark) {
        OsmCheckPlanInst order = osmCheckPlanInstMapper.selectByPrimaryKey(orderId);
        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setOperateUserName(UserDataUtil.getStaffName(request));
        flow.setOperateUserId(UserDataUtil.getStaffId(request));
        flow.setStatus(new Byte("1"));
        flow.setOrderId(orderId);
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setSimpleDesc(remark);
        order.setStatus("14");
        osmOrderFlowMapper.insertSelective(flow);
        osmCheckPlanInstMapper.updateByPrimaryKeySelective(order);

        LogCollector.INSTANCE.put("工单号",order.getOrderNbr());

        String content = "您处理的工单【"+order.getCheckTitle() +"】被退回，请重新处理";
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("order_type","2");
        jsonObject.addProperty("type","1");
        jsonObject.addProperty("order_id",order.getId());
        String extra = GsonUtil.toJson(jsonObject);
        String title = "收到派单";
        String sender = UserDataUtil.getStaffId(request);
        String target = order.getAcceptStaffId();
        CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,sender,target,order.getEnterpriseId());
        notifyUtil.send(createNotifyReq);
    }

    @Override
    public void cancel(HttpServletRequest request, String orderId) {

    }

    @Override
    public void confirm(HttpServletRequest request, String orderId) {
        OsmCheckPlanInst order = osmCheckPlanInstMapper.selectByPrimaryKey(orderId);

        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setOperateUserName(UserDataUtil.getStaffName(request));
        flow.setOperateUserId(UserDataUtil.getStaffId(request));
        flow.setStatus(new Byte("1"));
        flow.setOrderId(orderId);
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setSimpleDesc("确认工单完成");
        order.setStatus("8");
        osmOrderFlowMapper.insertSelective(flow);
        osmCheckPlanInstMapper.updateByPrimaryKeySelective(order);

        String content = "您处理的工单【"+order.getCheckTitle() +"】已确认";
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("order_type","2");
        jsonObject.addProperty("type","1");
        jsonObject.addProperty("order_id",order.getId());
        String extra = GsonUtil.toJson(jsonObject);
        String title = "收到派单";
        String sender = UserDataUtil.getStaffId(request);
        String target = order.getAcceptStaffId();
        CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,sender,target,order.getEnterpriseId());

        notifyUtil.send(createNotifyReq);

        LogCollector.INSTANCE.put("工单号",order.getOrderNbr());
    }

    @Override
    public void dispatch(ReqAssignOrder reqAssignOrder, HttpServletRequest request) {
        OsmCheckPlanInst order = osmCheckPlanInstMapper.selectByPrimaryKey(reqAssignOrder.getOrder_id());


        order.setAcceptStaffId(reqAssignOrder.getTarget_id());
        order.setStatus("5");
        order.setUpdateTime(new Date());
        osmCheckPlanInstMapper.updateByPrimaryKeySelective(order);

        //记录操作流程节点
        OsmOrderFlow osmOrderFlow = new OsmOrderFlow();
        osmOrderFlow.setSimpleDesc("指派给："+reqAssignOrder.getTarget_name());
        osmOrderFlow.setOperateUserId(reqAssignOrder.getOperate_staff_id());
        osmOrderFlow.setId(UuidUtil.getRandomUuid());
        osmOrderFlow.setOperateUserName(UserDataUtil.getStaffName(request));
        osmOrderFlow.setStatus(new Byte("1"));
        osmOrderFlow.setCreateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setUpdateTime(Integer.valueOf(String.valueOf(System.currentTimeMillis()/1000)));
        osmOrderFlow.setOperateUserName(reqAssignOrder.getOperate_staff_name());
        osmOrderFlow.setOrderId(order.getId());
        osmOrderFlow.setOperateUserIcon(reqAssignOrder.getOperate_staff_icon());
        osmOrderFlowMapper.insertSelective(osmOrderFlow);


        String content = "收到指派工单【"+order.getCheckTitle() +"】，快去接单吧";
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("order_type","2");
        jsonObject.addProperty("type","1");
        jsonObject.addProperty("order_id",order.getId());
        String extra = GsonUtil.toJson(jsonObject);
        String title = "收到派单";
        String sender = reqAssignOrder.getOperate_staff_id();
        String target = reqAssignOrder.getTarget_id();
        CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,sender,target,order.getEnterpriseId());

        notifyUtil.send(createNotifyReq);
    }


}
